package edu.byu.intex2.data.dao;

import edu.byu.intex2.data.Cache;
import edu.byu.intex2.data.ConnectionPool;
import edu.byu.intex2.data.DataException;
import edu.byu.intex2.data.bo.ConceptualCar;
import java.sql.*;

/**
  * @author Jason Whiting
 */
public class ConceptualCarDAO
{

    /////////////////////////////////////////////
    ///   Singleton code
    private static ConceptualCarDAO instance = null;

    /** Creates a new instance of ConceptualCarDAO */
    private ConceptualCarDAO()
    {
    }//constructor

    /** Retrieves the single instance of this class */
    public static synchronized ConceptualCarDAO getInstance()
    {
        if (instance == null)
        {
            instance = new ConceptualCarDAO();
        }
        return instance;
    }//getInstance

    ////////////////////////////////////////////
    ///   CREATE methods
    /**
     * Creates a new conceptualCar in the database */
    public ConceptualCar create(String id) throws DataException
    {
        ConceptualCar conceptualCar = new ConceptualCar(id);
        conceptualCar.setObjectAlreadyInDB(false);
        Cache.getInstance().put(conceptualCar.getId(), conceptualCar);
        return conceptualCar;
    }//create


    ////////////////////////////////////////////
    ///   READ methods
    /**
     * Reads an existing conceptualCar from the database     */
    public ConceptualCar read(String id) throws DataException
    {
        // Check Cache
        if (Cache.getInstance().containsKey(id))
        {
            return (ConceptualCar) Cache.getInstance().get(id);
        }

        // Get Connection
        Connection conn = ConnectionPool.getInstance().get();

        // Try Reading with connection
        try
        {
            return read(id, conn);
        } catch (Exception e)
        {
            throw new DataException("An error occurred while reading the business object information.", e);
        } finally
        {
            ConnectionPool.getInstance().release(conn);
        }
    }

    /**
     * Internal method to read an existing conceptualCar from the database
     * @return conceptualCar
     */
    synchronized ConceptualCar read(String id, Connection conn) throws Exception
    {
        // Check Cache
        if (Cache.getInstance().containsKey(id))
        {
            return (ConceptualCar) Cache.getInstance().get(id);
        }

        // Prepare a SQL Statement
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM conceptual_car where id=?");

        try
        {
            stmt.setString(1, id);
            ResultSet rs = stmt.executeQuery(); // execute query
            if (rs.next())
            {
                // Read the record with the result set
                return readRecord(rs, conn);
            }//if
            throw new DataException("ConceptualCar with id '" + id + "' not found.");
        } finally
        {
            stmt.close();
        }
    }//read

    /** Internal method to create a conceptualCar object from a record  */
    synchronized ConceptualCar readRecord(ResultSet rs, Connection conn) throws Exception
    {
        if (Cache.getInstance().containsKey(rs.getString("id")))
        {
            return (ConceptualCar) Cache.getInstance().get(rs.getString("id"));
        }
        // Create new conceptualCar object
        ConceptualCar conceptualCar = new ConceptualCar(rs.getString("id"));

        // ConceptualCar is already in DB
        conceptualCar.setObjectAlreadyInDB(true);

        // Put conceptualCar in cache
        Cache.getInstance().put(conceptualCar.getId(), conceptualCar);

        // Set ConceptualCar Attributes
        conceptualCar.setMake(rs.getString("make"));
        conceptualCar.setModel(rs.getString("model"));
        conceptualCar.setYear(rs.getInt("car_year"));
        conceptualCar.setBasePrice(rs.getDouble("base_price"));

        // ConceptualCar is dirty and needs to be saved to DB
        conceptualCar.setDirty(false);

        return conceptualCar;
    }//readRecord


    /////////////////////////////////////////////
    ///   UPDATE methods
    /** Saves an existing conceptualCar in the database */
    public void save(ConceptualCar conceptualCar) throws DataException
    {
        // get a connection from the pool, save all of the sales first using the other conceptualCar method and then commit them in the database
        Connection conn = ConnectionPool.getInstance().get();

        try
        {
            save(conceptualCar, conn); // save with connection
            conn.commit();  // commit the db transaction
        } catch (Exception e)
        {
            try
            {
                //rollback if there were any errors saving, catch any other errors you might have
                conn.rollback();
            } catch (SQLException e2)
            {
                throw new DataException("Could not roll back the conceptualCar database transaction!", e2);
            }
            throw new DataException("An error occurred while saving the conceptualCar object information.", e);
        } finally
        {
            // release the connection
            ConnectionPool.getInstance().release(conn);
        }
    }

    /** Internal method to update a conceptualCar in the database */
    void save(ConceptualCar conceptualCar, Connection conn) throws Exception
    {
        // put the conceptualCar object to cache
        Cache.getInstance().put(conceptualCar.getId(), conceptualCar);

        // decide whether to update or insert into the database
        if (conceptualCar.isObjectAlreadyInDB() && conceptualCar.isDirty())
        {
            update(conceptualCar, conn);
        } else if (conceptualCar.isDirty())
        {
            insert(conceptualCar, conn);
        }//if
    }

    /** External method to update or create a conceptualCar in the database without committing connection */
    public void saveNoCommit(ConceptualCar conceptualCar, Connection conn, Boolean alreadyInDB) throws Exception
    {
        // decide whether to update or insert into the database
        if (alreadyInDB)
        {
            update(conceptualCar, conn);
        } else
        {
            insert(conceptualCar, conn);
        }
    }

    /** Saves an existing conceptualCar to the database */
    private void update(ConceptualCar conceptualCar, Connection conn) throws Exception
    {
        // use a prepared statement to prevent sql injection
        PreparedStatement stmt = conn.prepareStatement("UPDATE conceptual_car SET make=?, model=?, car_year=?, base_price=?  WHERE id=?");
        try
        {
            // Get ConceptualCar Attributes and add them to the statement
            stmt.setString(1, conceptualCar.getMake());
            stmt.setString(2, conceptualCar.getModel());
            stmt.setInt(3, conceptualCar.getYear());
            stmt.setDouble(4, conceptualCar.getBasePrice());
            stmt.setString(5, conceptualCar.getId());
            stmt.execute();

            // ConceptualCar is clean!
            conceptualCar.setDirty(false);
        } finally
        {
            stmt.close();  // make sure to close the prepared statement
        }
    }

    /** Inserts a new conceptualCar into the database */
    private void insert(ConceptualCar conceptualCar, Connection conn) throws Exception
    {
        PreparedStatement stmt = conn.prepareStatement("INSERT INTO conceptual_car (id, make, model, car_year, base_price) VALUES (?, ?, ?, ?, ?)");
        try
        {
            // Set ConceptualCar Attributes
            stmt.setString(1, conceptualCar.getId());
            stmt.setString(2, conceptualCar.getMake());
            stmt.setString(3, conceptualCar.getModel());
            stmt.setInt(4, conceptualCar.getYear());
            stmt.setDouble(5, conceptualCar.getBasePrice());
            stmt.execute();

            conceptualCar.setObjectAlreadyInDB(true); // now in DB
            conceptualCar.setDirty(false); // object is clean
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            stmt.close(); // close the prepared statement
        }
    }

    /////////////////////////////////////////////////
    ///   DELETE methods
    /** We do not support deleting of business objects in this application */
    public void delete(ConceptualCar conceptualCar) throws DataException
    {
        throw new RuntimeException("Nice try. The delete function is not supported in this application.");
    }
}
